package com.wechat.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.wechat.entity.PaymentResult;
import com.wechat.service.WeChatPaymentService;
import com.wechat.utiltools.basic.ValueUtil;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;


@RestController
@RequestMapping("/pay")
public class PayController {


//            (required = false)//等他用的时候自动注入
    @Autowired
    private WeChatPaymentService paymentService;

    @RequestMapping(method = RequestMethod.POST)
    public String pay(String orderNumber, Double amount, Integer userId, String title, String description, HttpServletRequest request, HttpServletResponse response) {
        if(ValueUtil.isEmpity(orderNumber)){
            return ValueUtil.toJson(HttpStatus.SC_INTERNAL_SERVER_ERROR,"订单号不能为空");
        }
        PaymentResult paymentResult = paymentService.pay(orderNumber, amount, title, description, userId, request);
       String text = paymentResult.getData();
        int width = 100;
        int height = 100;
        String format = "png";
        Hashtable hints= new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
       BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);
        } catch (WriterException e) {
         ValueUtil.toError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
        File outputFile = new File("new.png");
        //第一种方法
             String base64code = null;
        try {
            MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html; charset=UTF-8");
         response.setContentType("image/jpeg");
        ByteArrayOutputStream newos = new ByteArrayOutputStream();//新建流。
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
        try {
            ImageIO.write(image, format, newos);//利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
        } catch (IOException e) {
            e.printStackTrace();
        }
            byte b[] = newos.toByteArray();//从流中获取数据数组。
            BASE64Encoder encoder = new BASE64Encoder();
             base64code = encoder.encode(b);
            System.out.println("图片："+base64code);
            return ValueUtil.toJson(HttpStatus.SC_CREATED,base64code);
        //第二种方法
       /* try {
            MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
            response.setContentType("text/html; charset=UTF-8");
            response.setContentType("image/jpeg");
            FileInputStream fis = new FileInputStream(outputFile);
            OutputStream os = response.getOutputStream();
            try
            {
                int count = 0;
                byte[] buffer = new byte[1024 * 1024];
                while ((count = fis.read(buffer)) != -1)
                    os.write(buffer, 0, count);
                os.flush();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                if (os != null)
                    os.close();
                if (fis != null)
                    fis.close();
            }
        } catch (IOException e) {
            return ValueUtil.toError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
        return null;*/

    }









//    @RequestMapping(value = "/app", method = RequestMethod.POST)
//    public String appPay(String orderNumber, Double amount, String payment, Integer userId, String title, String description, HttpServletRequest request, HttpServletResponse response) {
//
//        try {
//            TransactionHistory transactionHistory = transactionService.findByOrderId(orderNumber);
//            ValueUtil.verifyExist(transactionHistory, "该交易已完成");
//            Payment pay = Payment.getPayment(payment);
//            WeChatPaymentService paymentService = payFactory.getInstance(pay);
//            PaymentResult paymentResult = paymentService.appPay(orderNumber, amount, title, description, userId, request);
////            if (pay.equals(Payment.WeChat) && paymentResult.getCode().equals("SUCCESS")) {
////                String urlCode = paymentResult.getData();
////                try {
////                    QRCodeUtils.qrCodeEncode(urlCode, "QR");
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
////                response.setContentType("text/html; charset=UTF-8");
////                response.setContentType("image/jpeg");
////                FileInputStream fis = null;
////                fis = new FileInputStream("QR" + ".png");
////                OutputStream os = null;
////                os = response.getOutputStream();
////                int count = 0;
////                byte[] buffer = new byte[1024 * 1024];
////                while ((count = fis.read(buffer)) != -1) {
////                    os.write(buffer, 0, count);
////                }
////                os.flush();
////                return ValueUtil.toJson(paymentResult);
////            }
//
//            return ValueUtil.toJson(paymentResult.getData());
//        } catch (YesmywineException e) {
//            return ValueUtil.toError(e.getCode(), e.getMessage());
//        }
//    }


/*    @RequestMapping(value = "/refund", method = RequestMethod.POST)
    public String refund(String orderNumber, Double payAmount, Double refundAmount, String refundNumber, String title, String description,String queryId ) {

        try {
            return ValueUtil.toJson(paymentService.refund(orderNumber,refundNumber, payAmount, refundAmount, title, description,queryId));
        } catch (Exception e) {
            e.printStackTrace();
            return ValueUtil.toError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "退款失败");
        }

    }

    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public String queryDetail(String orderId) {
        try {
            return ValueUtil.toJson(paymentService.queryDetail(orderId));
        } catch (Exception e) {
            return ValueUtil.toError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "查询失败");
        }
    }*/

}
